package ddd.ajava.chapter5.question2.tcp;

import java.net.*;
import java.io.*;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class ThreadForOne implements Runnable {
	Socket client;

	public ThreadForOne(Socket client) {
		this.client = client;
	}

	public void run() {// 一个会话的内容
		BufferedReader read;
		try {
			// 从客户端得到数据流
			read = new BufferedReader(new InputStreamReader(
					this.client.getInputStream()));
			PrintStream write = new PrintStream(this.client.getOutputStream());

			// 到文件的输入输出流
			String fileName = read.readLine();
			// File file=new File("upload",fileName);//得到文件的名字
			File file = new File(fileName);// 得到文件的名字
			PrintStream writeFile = new PrintStream(file);

			// 服务端接受客户端的信息（文件内容）
			char[] chars = new char[1024];
			read.read(chars);

			// 写入文件
			for (int i = 0; i < chars.length; i++) {
				writeFile.print(chars[i]);
			}

			String response = "文件已经收到！";
			FileInformation("文件名：" + fileName);
			write.println(response);
			write.flush();

			read.close();
			write.close();
			writeFile.close();
			this.client.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void FileInformation(String texts) {// 显示收到的文本
		JFrame showInfo = new JFrame();
		JPanel jp = new JPanel();
		JTextArea text = new JTextArea(20, 20);// 文本区
		text.append(texts);// 输入
		jp.add(text);
		showInfo.add(jp);

		showInfo.setTitle("服务端相应！");
		showInfo.setVisible(true);
		showInfo.setSize(300, 100);
		showInfo.setLocation(500, 500);
		showInfo.setDefaultCloseOperation(1);
	}
}
